package core

import (
	"gitee.com/molonglove/goboot/gorm"
	"gitee.com/molonglove/goboot/gorm/driver/sqlite"
	"gitee.com/molonglove/goboot/gorm/logger"
	"gitee.com/molonglove/goboot/gorm/schema"
	"github.com/mitchellh/go-homedir"
	"helper-api/app/models/entity"
	"helper-api/utils"
	"log"
	"os"
	"path/filepath"
	"time"
)

var DB *gorm.DB

const (
	GetTable  = "SELECT name FROM sqlite_master WHERE type='table'"
	AdminData = "INSERT INTO s_user (id, username, phone, email, salt, password, can_view) VALUES (1, 'admin', '15711119999', 'xxx@qq.com', 'Lucky.麒麟', '4da32d37a1a3b3728d49c1f9b5010ef0', 1)"
)

func Sqlite() {
	var (
		db          *gorm.DB
		newLogger   logger.Interface
		tablePrefix = "s_"
		tables      []string
		dbPath      string
		err         error
		tableMap    = map[string]any{
			"s_role":            entity.Role{},
			"s_user":            entity.User{},
			"s_script":          entity.Script{},
			"s_software":        entity.Software{},
			"s_user_role":       entity.UserRole{},
			"s_permission":      entity.Permission{},
			"s_role_permission": entity.RolePermission{},
			"s_execute":         entity.Execute{},
		}
	)

	newLogger = logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second,   // 慢 SQL 阈值
			LogLevel:                  logger.Silent, // 日志级别
			IgnoreRecordNotFoundError: true,          // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,         // 禁用彩色打印
		},
	)
	newLogger.LogMode(logger.Info)
	dbPath, _ = homedir.Expand("~/.helper/database.db")
	if db, err = gorm.Open(sqlite.Open(filepath.FromSlash(dbPath)), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   tablePrefix,
			SingularTable: true,
		},
	}); err != nil {
		Log.Error("打开数据库文件失败 => %s", err.Error())
		panic(err)
	}
	if err = db.Raw(GetTable).Scan(&tables).Error; err != nil {
		panic("获取数据失败表")
	}
	for key, value := range tableMap {
		if exist, _ := utils.In[string](key, tables); !exist {
			if err = db.AutoMigrate(&value); err != nil {
				Log.Error("生成数据表失败 => %s", err.Error())
				panic("初始化数据表失败")
			}
			if key == "s_user" {
				if err = db.Exec(AdminData).Error; err == nil {
					Log.Info("生成系统账号[%s],密码[%s]，请进入系统修改账号密码", "admin", "123456")
				}
			}
		}
	}
	Log.Info("初始化数据库成功")
	DB = db
}
